/**
 * @FileName: DeviceFragment.java
 * @Package:com.bdtop.dbl.ui.fragments
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-26
 * @version V1.0
 */

package com.bdtop.dbl.ui.activities.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.bdtop.dbl.BaseFragment;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.device.DeviceInfoActivity;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.adapters.DeviceListAdapter;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: DeviceFragment
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-26
 */
public class DeviceFragment extends BaseFragment {

    private ListView mDeviceListView;

    public DeviceListAdapter mDeviceListAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device_list, container, false);
        initViews(view);
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            TextView tx = holder.getWaitingText();
            if (tx.getText().toString().equals(getString(R.string.wating_get_device_list))) {
                holder.showWaitingMessage();
            } else if (mDeviceListAdapter.getList() == null
                    || mDeviceListAdapter.getList().size() == 0) {
//                holder.setAndShowWaitingMessage(R.string.no_device_bind);
            } else {
                holder.hiddenWaitingMessage();
            }
        } else {
            holder.hiddenWaitingMessage();
        }
    }

    public void init() {
        mDeviceListAdapter.setList(DBLApplication.getInstance().deviceInfoList);
        mDeviceListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (DBLApplication.getInstance().deviceInfoList != null) {
            init();
        }
    }

    private void initViews(View view) {

        mDeviceListView = (ListView) view.findViewById(R.id.device_list);
        mDeviceListView.setOnItemClickListener(mOnItemClickListener);
        mDeviceListView.setOnItemLongClickListener(mOnItemLongClickListener);

        mDeviceListAdapter = new DeviceListAdapter(getActivity());
        mDeviceListView.setAdapter(mDeviceListAdapter);
    }

    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int index, long itemId) {
        	if(DBLApplication.getInstance().deviceInfoList != null){
        		DeviceInfoActivity.launch(getActivity(),
        				DBLApplication.getInstance().deviceInfoList.get(index));
        	}
        }
    };

    private OnItemLongClickListener mOnItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
            Vibrator mVibrator = (Vibrator) holder.getApplication().getSystemService(
                    Service.VIBRATOR_SERVICE);
            mVibrator.vibrate(100);
            DeviceInfo dd = DBLApplication.getInstance().deviceInfoList.get(position);
            showDeleteDialog(dd.mdn);

            return true;
        }
    };

    private void showDeleteDialog(final String mdn) {
        final Dialog dialog = new Dialog(holder, R.style.Theme_Light_NoTitle_Dialog);
        View content = LayoutInflater.from(holder).inflate(R.layout.dialog_confirm_2, null);

        TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
        txMessage.setText(R.string.deleteTip);

        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();

                if (arg0.getId() == R.id.btn_confirm) {
                    setAndShowWaitingMessage(R.string.wating_update);
                    String sign = Preferences.getLoginSign(holder);
                    ServerApiFactory.getApiImpl().deviceDel(sign, mdn, new RequestCallback() {
                        @Override
                        public void onSuccess(String rawData, Object response) {
                            clearAndHiddenWaitingMessage();
                            BaseResponse br = (BaseResponse) response;
                            showToast(br.getDesc());
                            if (br.getStatus().equals(Constants.REQUEST_SUCCESS)) {
                            	// 如果删除的是当前设备，将当前设备引用置空
                                if (mdn.equals(DBLApplication.getInstance().currentDi)) {
                                    DBLApplication.getInstance().currentDi = null;
                                }
                                // 在列表中找到该设备并且删除
                                if(DBLApplication.getInstance().deviceInfoList != null){
                                	for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
                                        if (di.mdn.equals(mdn)) {
                                            DBLApplication.getInstance().deviceInfoList.remove(di);
                                            
                                            if(holder != null){
                                            	((MainActivity)holder).initDeviceList();
                                            }
                                            break;
                                        }
                                    }
                                }
                                // 重新设置第一个为当前默认设备
                                if(DBLApplication.getInstance().deviceInfoList.size() > 0){
                                	DBLApplication.getInstance().currentDi = DBLApplication.getInstance().deviceInfoList.get(0);
                                }
                                
                                // 解除蓝牙绑定
                                Preferences.saveImeiForMac(holder, mdn, "");
                            }
                        }

                        @Override
                        public void onError(int statusCode, Throwable e, String rawData) {
                            clearAndHiddenWaitingMessage();
                            showToast(R.string.net_error);
                            if (NetworkUtils.isNetConnect(holder)) {
                                showToast(R.string.oper_error);
                            } else {
                                showToast(R.string.net_error);
                            }
                        }
                    });
                }
            }
        };

        content.findViewById(R.id.btn_confirm).setOnClickListener(listener);
        content.findViewById(R.id.btn_cancel).setOnClickListener(listener);

        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(content);
        dialog.show();
    }

}
